package com.sec.etech.employeesync.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployee;
import com.sec.etech.employeesync.mapper.OrgEmployeeMapper;
import com.sec.etech.employeesync.util.EmployeeDataConverter;
import com.sec.etech.employeesync.util.EmployeeFilterHandler;
import com.sec.etech.employeesync.util.MainWorkExperienceHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
@Deprecated
public class EmployeeDataSyncService {

    @Resource
    private OrgEmployeeMapper orgEmployeeMapper;
    @Autowired
    private MainWorkExperienceHandler mainWorkExperienceHandler;
    @Autowired
    private EmployeeDataConverter employeeDataConverter;
    @Autowired
    private EmployeeFilterHandler employeeFilterHandler;

    @Transactional
    public void syncEmployeeData(JSONObject resultObj) {
        JSONObject data = resultObj.getJSONObject("data");
        JSONArray etResultArray = data.getJSONArray("ET_RESULT");
        JSONArray etPa0001Array = data.getJSONArray("ET_PA0001");

        for (int i = 0; i < etResultArray.size(); i++) {
            JSONObject employeeData = etResultArray.getJSONObject(i);

            if (!employeeFilterHandler.isEmployeeFilter(employeeData)) {
                log.info("员工不满足处理条件，跳过: {}", employeeData.getString("PERNR"));
                continue;
            }

            OrgEmployee employee = employeeDataConverter.convertToOrgEmployee(employeeData);

            // 检查员工是否已存在
            OrgEmployee existingEmployee = orgEmployeeMapper.selectOne(Wrappers.<OrgEmployee>lambdaQuery()
                    .eq(OrgEmployee::getAccount, employee.getAccount()));

            if (existingEmployee == null) {
                // 新增员工
                orgEmployeeMapper.insert(employee);
                log.info("新增员工: {}", employee.getAccount());
            } else {
                // 更新员工
                employee.setEmployeeid(existingEmployee.getEmployeeid());
                orgEmployeeMapper.updateById(employee);
                log.info("更新员工: {}", employee.getAccount());
            }

            // 处理主业经历
            JSONArray employeeMainWorkExperience = etPa0001Array.stream()
                    .map(item -> (JSONObject) item)
                    .filter(item -> item.getString("PERNR").equals(employeeData.getString("PERNR")))
                    .collect(JSONArray::new, JSONArray::add, JSONArray::addAll);

            mainWorkExperienceHandler.handleMainWorkExperience(employee.getEmployeeid(), employeeMainWorkExperience);
        }
    }
}
